package me.kuye.jkuye.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.kuye.jkuye.helper.DatabaseHelper;
import me.kuye.jkuye.plugin.activerecord.Config;

public class DatabaseUtil {
	private final Config config;
	private static final Map<String, DatabaseUtil> databaseUtilMap = new HashMap<String, DatabaseUtil>();

	public DatabaseUtil() {
		if (DatabaseHelper.config == null) {
			throw new RuntimeException(" the main config can not be  null");
		}
		this.config = DatabaseHelper.config;
	}

	public DatabaseUtil(String configName) {
		this.config = DatabaseHelper.getConfig(configName);
		if (this.config == null) {
			throw new IllegalArgumentException(" the main config can not be null");
		}
	}

	public static DatabaseUtil use(String configName) {
		DatabaseUtil databaseUtil = databaseUtilMap.get(configName);
		if (databaseUtil == null) {
			databaseUtil = new DatabaseUtil(configName);
			databaseUtilMap.put(configName, databaseUtil);
		}
		return databaseUtil;
	}

	public static DatabaseUtil use() {
		return use(DatabaseHelper.config.getName());
	}

	public <T> List<T> query(Config config, Connection connection, String sql, Object[] args) {
		List result = new ArrayList();
		try {
			PreparedStatement preparedStatement = connection.prepareStatement(sql);
			config.getDialect().fillStatement(preparedStatement, args);
			ResultSet resultSet = preparedStatement.executeQuery();
			int columnCount = resultSet.getMetaData().getColumnCount();
			if (columnCount > 1) {
				while (resultSet.next()) {
					Object[] temp = new Object[columnCount];
					for (int i = 0; i < columnCount; i++) {
						temp[i] = resultSet.getObject(i + 1);
					}
					result.add(temp);
				}
			} else if (columnCount == 1) {
				while (resultSet.next()) {
					result.add(resultSet.getObject(1));
				}
			}
			DatabaseHelper.closeQuietly(resultSet, preparedStatement);
		} catch (SQLException e) {
			e.printStackTrace();
		}

		return result;
	}
}
